<?php

namespace app\admin\controller\service_config;

use app\common\model\admin\service_config\ServiceConfigData;
use app\common\model\admin\service_config\ServiceConfigRule;
use app\common\model\admin\service_config\ServiceConfigTab;
use app\common\model\admin\service_config\ServiceConfigTabAccount;
use app\common\model\admin\AccountModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;

/**
 *  公司服务配置
 * @class ConfigTabCompany
 * @package app\admin\controller\service_config
 * @Author: shirukun
 * @Date: 2024/11/7 17:54
 */
class ConfigTabCompany extends Controller
{

    /**
     * 默认检测登陆后台用户
     *
     * @var bool
     */
    public $check_user = false;

    /**
     *  配置管理
     * @auth true
     * @menu true
     */
    public function index()
    {
        ServiceConfigTabAccount::mQuery()->layTable(function () {
            $this->title = lang('配置管理');
//            $this->types = SystemBase::mk()->where(['deleted' => 0])->where(['type' => '配置分类'])->distinct()->column('name,code');
            $this->types = array_map('lang', ServiceConfigTab::$types);
            $this->type = $this->get['type'] ??  key($this->types);

            $this->group = ServiceConfigTab::mk()->where(['status' => 1,'type'=>$this->type])->field('type,name,code')->select()->toArray();
//            halt($this->group);

            $this->account_list = AccountModel::column("title","id");

        }, function (QueryHelper $query) {

            // 数据权限
            $query->where(function ($query) {
                if (!$this->super) {
                    $query->where(['account_id'=>$this->adminUser['account_id']]);
                }
            });

            // 数据列表搜索过滤
            $query->equal('code,group,type,status,account_id')->like('alias_name#alias_name')->dateBetween('create_time');
        });
    }

    protected function _index_page_filter(&$data)
    {
//        halt($data);
        // 配置分组
        $group = ServiceConfigTab::mk()->where(['status' => 1])->select();
//        halt($group->toArray());
        //公司
        $company = AccountModel::column("title","id");
        foreach ($data as &$item) {
            $item['company_name'] = $company[$item['account_id']] ?? "-";

            $item['group_name'] = "-";
            foreach ($group as $v){
                if($item['type'] == $v['type'] && $item['group'] == $v['code']){
                    $item['group_name'] = $v['name'];
                }
            }
        }
    }

    /**
     * 添加配置
     * @auth true
     */
    public function add()
    {
//        $this->_applyFormToken();
        ServiceConfigTabAccount::mForm('form');
    }

    /**
     * 编辑配置
     * @auth true
     */
    public function edit()
    {
//        $this->_applyFormToken();
        ServiceConfigTabAccount::mForm('form');
    }

    /**
     * 表单数据处理
     * @param array $vo
     * @throws \ReflectionException
     */
    protected function _form_filter(array &$vo)
    {
        if ($this->request->isGet()) {
            $this->companys = AccountModel::mq()->select();
            $this->types = array_map('lang', ServiceConfigTab::$types);
            $this->type = $this->get['type'];
            $this->group = ServiceConfigTab::mk()->where(['status' => 1,'type'=>$this->type])->field('type,name,code')->select()->toArray();
        }else{
            $param = $this->request->param();

            $rule = [
                "account_id|".lang('平台')    =>  "require|integer",
                "type|".lang('配置类型')    =>  "require|max:50",
                "group|".lang('配置名称')    =>  "require|max:50",
                "alias_name|".lang('配置别名')    =>  "require|max:100",
                "status|".lang('状态')    =>  "in:1,0",
                "sort|".lang('排序')    =>  "integer",
                "note|".lang('备注')    =>  "max:255",
            ];
            $validate = new \think\Validate;

            // 验证规则
            $validate->rule($rule);
            if (!$validate->check($param)) {
                $this->error($validate->getError());
            }

            if (!isset($param['id'])){
                $res = ServiceConfigTabAccount::mk()->where(['account_id'=>$param['account_id'],'type' => $param['type'],'alias_name' => $param['alias_name']])->find();
                if ($res){
                    return $this->error(lang("此分组别名已存在"));
                }
            }
        }
    }

    /**
     * 修改数据状态
     * @auth true
     */
    public function state()
    {
        ServiceConfigTabAccount::mSave($this->_vali([
            'status.in:1,0'  => lang('状态值范围异常'),
            'status.require' => lang('状态值不能为空'),
        ]));
    }

    /**
     * 删除配置
     * @auth true
     */
    public function remove()
    {
        // todo 删除子表

        ServiceConfigTabAccount::mDelete();
    }


    /**
     * 配置参数
     * @auth true
     */
    public function set_data()
    {
        $param = $this->request->param();

        // 公司配值分组
        $this->vo = ServiceConfigTabAccount::mq()->where(['id'=>$param['id']])->find();

        // 提交配置数据
        if ($this->request->isPost()){

            $data = [];
            $i = 0;
            foreach ($param as $k => $v){

                if(in_array($k,['file','id'])) continue;

                $data[$i]['account_group_id'] =  $this->vo['id'];
                $data[$i]['account_id'] =  $this->vo['account_id'];
                $data[$i]['type'] =  $this->vo['type'];
                $data[$i]['group'] =  $this->vo['group'];
                $data[$i]['code'] =  $k;

                if(is_array($v)){
                    $data[$i]['value'] = json_encode($v,320);
                }else{
                    $data[$i]['value'] = $v;
                }

                ++$i;
            }
//            halt($data);

            try {
                // 删除历史配值
                ServiceConfigData::where(['account_group_id'=>$this->vo['id']])->delete();
                // 添加新数据
                (new ServiceConfigData())->saveAll($data);

            }catch (\Exception $e){
//                halt($e);
                $this->error($e->getMessage());
            }

            $this->success(lang('配置成功'));
        }

        // 系统配值规则
        $this->config_rule = ServiceConfigRule::mq()->where(['type'=>$this->vo['type'],'group'=>$this->vo['group'],'status'=>1])
            ->order('sort desc')->select()->toArray();
        foreach ($this->config_rule as &$v){
            // 是否包含字符
            $v['is_required'] = preg_match('/required/', $v['required']);
            $v['parameter'] = empty($v['parameter']) ? [] : explode(',',$v['parameter']);
            foreach ($v['parameter'] as &$parameter){
                $parameter = explode('=>',$parameter);
            }
        }
//        halt($this->config_rule);
        // 公司配值数据
        $ServiceConfigData = ServiceConfigData::mq()->where(['account_group_id'=>$this->vo['id']])
            ->select()->toArray();

        $config_data = [];
        foreach ($ServiceConfigData as &$v){
            $config_data[$v['code']] = $v['value'];
        }
        $this->config_data = $config_data;

        return $this->fetch();

    }
}